﻿// ***********************************************************************
// Assembly         : TSharp.Core
// Author           : tangjingbo
// Created          : 08-25-2013
//
// Last Modified By : tangjingbo
// Last Modified On : 08-25-2013
// ***********************************************************************
// <copyright file="WindowsSecurityUtil.cs" company="Extendsoft">
//     Copyright (c) Extendsoft. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text;

namespace TSharp.Core.Security
{
    /// <summary>
    /// Enum PermissionCheck
    /// </summary>
    public enum PermissionCheck
    {
        /// <summary>
        /// 当前用户无法获取管理员权限
        /// </summary>
        NoAdministrator,
        /// <summary>
        /// 当前用户为管理员
        /// </summary>
        Administrator,
        /// <summary>
        /// 正在重启尝试获取管理员
        /// </summary>
        RestartTryGet,
    }
    /// <summary>
    /// Class WindowsSecurityUtil
    /// </summary>
    public static class WindowsSecurityUtil
    {

        /// <summary>
        /// Runs as administrator.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <param name="executablePath">The executable path.</param>
        /// <returns>PermissionCheck.</returns>
        public static PermissionCheck RunAsAdministrator(string[] args, string executablePath)
        {
            var identity = WindowsIdentity.GetCurrent();
            if (identity != null && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator))
            {
                return PermissionCheck.Administrator;
            }
            if (args != null && args.Contains("-selfcall"))
            {
                return PermissionCheck.NoAdministrator;
            }
            //创建启动对象
            var startInfo = new ProcessStartInfo
            {
                FileName = executablePath,
                Arguments = String.Join(" ", args.Concat(new[] { "-selfcall" })),
                Verb = "runas"
            };
            //设置运行文件

            //设置启动参数
            //设置启动动作,确保以管理员身份运行
            //如果不是管理员，则启动UAC
            Process.Start(startInfo);
            //退出
            return PermissionCheck.RestartTryGet;
        }
    }
}
